from os import strerror
import pygame,sys
from re import compile,findall
from socket import socket
from time import sleep

def getintfrom(stri) :
    '''检测[]中的数字'''
    stri = str(stri,encoding='utf-8')
    return findall(r"\[\s*(\d+)\s*\]",stri)

def initsk() :
    global sock
    sock = socket()
    sock.connect(('127.0.0.1',2300))


def setcfg() :
    global sock
    sock.send(b'C')
    l = getintfrom(sock.recv(1000000))
    global x,y
    x = int(l[1])
    y = int(l[0])


def mainloop(w,h):

    pygame.init()
    screen=pygame.display.set_caption('pyboard2')
    screen=pygame.display.set_mode([h,w])
    screen.fill([255,255,255])
    pygame.display.flip()
    
    # fetchCacheFile(1)
    # loadCacheFile(screen)
    pygame.display.flip()
    
    while True:
        # fetchCacheFile(1)

        print('loadcache')
        prtn = compile(r"\[(\d*)\]\[(\d*)\]<#?([0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f]{2})([0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f]{2})([0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f]{2})>")
        f = open(sys.path[0]+'\\BoardCache.dat','r')
        ans = findall(prtn,f.read())

        cnt = 0
        for i in ans :
            # print(i)
            r =int('0x'+str(i[2]),16)
            g =int('0x'+str(i[3]),16)
            b =int('0x'+str(i[4]),16) 
            screen.set_at([int(i[0]),int(i[1])],[r,g,b])
            if cnt % 100 == 0 :
                pygame.display.flip()
            cnt += 1

        # loadCacheFile(screen)
        pygame.display.flip()
        
        f.close()

        # screen.set_at([x,y],[r,g,b])
        
        
        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                sys.exit()

        fetchCacheFile()
        sleep(0.5)

cached = 1

def fetchCacheFile():
    # global cached
    # print('fetchCache')
    n = open(sys.path[0]+'\\BoardCache.dat','wb+')
    global sock
    sock.send(b'G')
    
    num = cached

    # strr = "{:016X}".format(int(hex(num),16))
    # sock.send(bytes(strr,encoding='utf-8'))

    while True:
        strr = sock.recv(1048576)
        print(strr)
        n.write(strr)
        if b'E' in strr :
            break

    n.close()

    # cached = sock.recv(16)
    # print(int(str(cached,encoding='utf-8'),16))

    
    # sk.recv(128)
    # sk.recv(128)
    
    # while True:
    #     rec = sk.recv(16384)
    #     if  b'CloseSession' in rec :
    #         n.write(rec)
    #         print('OK!')
    #         n.close()
    #         break
    #     if rec :
    #         print('rec',rec)
    #         n.write(rec)




if __name__ == '__main__' :
    initsk()
    setcfg()
    fetchCacheFile()
    mainloop(y,x)
    # print(getintfrom("[12345678][333333333][]"))